package com.gjy.design.proxy.cglib;

import net.sf.cglib.proxy.MethodInterceptor;
import net.sf.cglib.proxy.MethodProxy;

import java.lang.reflect.Method;

/**
 * @author gjy
 * @version 1.0
 * @since 2025-11-10 10:52:36
 */

public class CglibLoggingInterceptor implements MethodInterceptor {

    private final Object target;

    public CglibLoggingInterceptor(Object target) {
        this.target = target;
    }

    @Override
    public Object intercept(Object obj, Method method, Object[] args,
                            MethodProxy proxy) throws Throwable {
        long start = System.currentTimeMillis();
        // 写法一：使用 methodProxy.invokeSuper 调用父类（目标对象）方法
//        Object result = proxy.invokeSuper(obj, args);
        // 写法二：使用 method.invoke(target, args) 直接调用原始对象
        Object result = method.invoke(target, args);
        long end = System.currentTimeMillis();
        System.out.println("[CGLIBProxy] method=" + method.getName() + ", cost=" + (end - start) + " ms");
        return result;
    }

}
